package com.mini.file.api.file;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.maxus.mini.common.Constants;
import com.maxus.mini.common.vo.ResBody;
import com.mini.file.api.vo.res.PR100099Vo;

/**
 * 文件controller
 * 
 * @author wujinsong
 *
 */
@RestController()
@RequestMapping(value = "api/v1.0/file")
public class FileController {

	/**
	 * 上传附件
	 * 
	 * @param req
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "upload")
	@ResponseBody()
	public ResBody upload(MultipartFile file,String path, HttpServletRequest request) {
		PR100099Vo retVo = new PR100099Vo();

		HashMap umap = this.uploadFile(file, Constants.ROOT_RES_DIR);
		retVo.setPath(umap.get("path").toString());

		return retVo;
	}

	/**
	 * 显示图片
	 * 
	 * @param picUrl
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "display")
	@ResponseBody()
	public void display(String picUrl, HttpServletRequest request, HttpServletResponse response) throws Exception {
		FileInputStream fis = null;
		OutputStream os = null;
		try {
			fis = new FileInputStream(Constants.ROOT_RES_DIR + picUrl);
			os = response.getOutputStream();
			int count = 0;
			byte[] buffer = new byte[1024 * 8];
			while ((count = fis.read(buffer)) != -1) {
				os.write(buffer, 0, count);
				os.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			fis.close();
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传附件
	 * 
	 * @param file
	 * @param path
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private HashMap uploadFile(MultipartFile file, String path) {
		InputStream in = null;
		OutputStream out = null;
		FileInputStream inStream = null;
		FileOutputStream outStream = null;
		String filePath = null;
		HashMap map = new HashMap();
		try {
			String uid = UUID.randomUUID().toString();
			uid = uid.toString().replace("-", "");
			StringBuilder stringBuilder = new StringBuilder();
			String name = file.getName();
			String suffix = "png";
			if (name.endsWith(".jpg"))
				suffix = "jpg";
			String dirName = Constants.df.format(System.currentTimeMillis());
			stringBuilder.append(path).append(Constants.RES_DIR).append("/").append(dirName);
			File dir = new File(stringBuilder.toString());
			if (!dir.exists())
				dir.mkdirs();
			stringBuilder.append("/").append(uid).append(".").append(suffix);
			File saveDir = new File(stringBuilder.toString());
			filePath = Constants.RES_DIR + "/" + dirName + "/" + uid + "." + suffix;
			in = file.getInputStream();
			out = new FileOutputStream(saveDir);
			byte[] buffer = new byte[5120];
			int len = 0;

			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			out.flush();

			in.close();

			in = file.getInputStream();
			BufferedImage inputBufImage = ImageIO.read(in);
			int width = inputBufImage.getWidth();
			int height = inputBufImage.getHeight();

			map.put("width", width);
			map.put("height", height);
			map.put("path", filePath);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null)
					out.close();
				if (in != null)
					in.close();
				if (inStream != null)
					inStream.close();
				if (outStream != null)
					outStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return map;
	}
}
